import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import '../components/contactItem.dart';
import '../pages/userDetail.dart';
import '../models/index.dart';

class AddFriendPage extends StatefulWidget {
  @override
  _AddFriendPageState createState() => _AddFriendPageState();
}

class _AddFriendPageState extends State<AddFriendPage> {
  TextEditingController keywordController = TextEditingController();
  List<User> _userList = [];
  //设置防抖周期为3s
  Duration durationTime = Duration(milliseconds: 300);
  Timer timer;
  List<String> myFriendList;

  getMyFriendList() async {
    var result = await FlutterWildfire.getMyFriendList(true);
    myFriendList = List.generate(result.length, (int index) => result[index]);
  }

  keywordControllerChangedHandler() async {
    final keyword = keywordController.text.trim();
    timer?.cancel();
    if (keyword.isEmpty) {
      _userList.clear();
      _userList = [];
      this.setState(() {});
      return;
    }

    timer = new Timer(durationTime, () async {
      //搜索函数
      print('搜索');
      var result = await FlutterWildfire.searchUser(keyword.trim(), true);
      _userList = List.generate(result.length, (i) => User.fromJson(result[i]));
      this.setState(() {});
    });
  }

  @override
  void initState() {
    getMyFriendList();
    keywordController.addListener(keywordControllerChangedHandler);
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    keywordController.dispose();
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.0),
                  child: TextField(
                    controller: keywordController,
                    decoration: InputDecoration(hintText: 'Search'),
                  ),
                ),
      ),
      body: Column(
        children: <Widget>[
          
          Expanded(
            child: ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return ContactItem(
                    onPressed: () {
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (context) {
                        return UserDetailPage(userData: _userList[index], isMyFriend: myFriendList.any((id) => id == _userList[index].uid),);
                      }));
                    },
                    title: _userList[index].displayName,
                    avatar: _userList[index].portrait.isEmpty
                        ? 'assets/images/default_nor_avatar.png'
                        : _userList[index].portrait,
                  );
                },
                itemCount: _userList.length),
          )
        ],
      ),
    );
  }
}
